package com.cloudkinto.service.region.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.RedisKeyConstants;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.JpRegionDao;
import com.cloudkinto.dao.JpStateDao;
import com.cloudkinto.entity.JpRegionDo;
import com.cloudkinto.entity.JpStateDo;
import com.cloudkinto.service.region.JpRegionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 日本都道府县以及对应邮编信息 service实现类
 * </p>
 *
 * @author hua
 * @since 2023-12-11
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class JpRegionServiceImpl extends ServiceImpl<JpRegionDao, JpRegionDo> implements JpRegionService {
    @Autowired
    private JpRegionDao dao;
    @Autowired
    private JpStateDao jpStateDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        JpRegionDo entityDo = new JpRegionDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(JpRegionDo entityDo, Long userId) {

    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(JpRegionDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*JpRegionDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(JpRegionDo entityDo, Long userId) {

    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(JpRegionDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        JpRegionDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(JpRegionDo entityDo, Long userId) {
    }

    @Override
    public Object detail(Long id) {
        JpRegionDo entityDo = dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<Object> getList(Map<String, String> map) {
        QueryWrapper<JpRegionDo> wrapper = queryBuild(map);
        List<JpRegionDo> list = this.list(wrapper);
        List<Object> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<JpRegionDo> wrapper = queryBuild(map);
        IPage<JpRegionDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<Object> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<JpRegionDo> list) {
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<JpRegionDo> pageInit(Map<String, String> map) {
        IPage<JpRegionDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<JpRegionDo> queryBuild(Map<String, String> map) {
        QueryWrapper<JpRegionDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }


    @Override
    public Object getRegionList() {
        Object o = redisTemplate.opsForValue().get(RedisKeyConstants.reRegionList);
        if (o == null) {
            List<JpStateDo> jpStateList = jpStateDao.selectList(null);
            List<JpRegionDo> jpRegionList = dao.selectList(null);
            Map<Long, List<JpRegionDo>> listMap = jpRegionList.stream().filter(i -> i.getJpStateId() != null).collect(Collectors.groupingBy(JpRegionDo::getJpStateId));
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (JpStateDo jpStateDo : jpStateList) {
                Map<String, Object> result = new HashMap<>();
                result.put("value", jpStateDo.getId());
                result.put("label", jpStateDo.getName());
                List<JpRegionDo> regionDos = listMap.get(jpStateDo.getId());
                if (regionDos != null) {
                    List<Map<String, Object>> regionDoListMap = new ArrayList<>();
                    for (JpRegionDo regionDo : regionDos) {
                        Map<String, Object> regionMap = new HashMap<>();
                        regionMap.put("value", regionDo.getId());
                        regionMap.put("label", regionDo.getName());
//                    regionMap.put("jpRegionId", regionDo.getId());

                        regionDoListMap.add(regionMap);
                    }
                    result.put("children", regionDoListMap);
                }
                resultList.add(result);
            }
            redisTemplate.opsForValue().set(RedisKeyConstants.reRegionList, resultList, 1000 * 60 * 60 * 12, TimeUnit.MILLISECONDS);
            return resultList;
        } else {
            return o;
        }
    }


    /**
     * 通过postCode 获取县
     *
     * @param code
     * @return
     */
    public Long getIdByPostCode(String code, String resultType) {
        QueryWrapper<JpRegionDo> wrapper = new QueryWrapper<>();
        String post2 = "";
        int postcode = 0;
        try {
            String regEx = "[^0-9||^０-９]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(code);
            post2 = m.replaceAll("").trim();
            if (post2.length() > 7)
                post2 = post2.substring(0, 7);
            postcode = Integer.parseInt(post2);
        } catch (NumberFormatException | NullPointerException e) {
            e.printStackTrace();
            return null;
        }
        if (postcode < 100000) {//北海道特殊地区
            postcode = 400001;
        }
        wrapper.le("post_code_start", postcode);
        wrapper.ge("post_code_end", postcode);
        JpRegionDo jpRegionDo = baseMapper.selectOne(wrapper);
        if (jpRegionDo == null) {
            return -1L;
        }
        if ("state".equals(resultType)) {
            return jpRegionDo.getJpStateId();
        } else {
            return jpRegionDo.getId();
        }
    }

    @Override
    public Long getStateIdByRegionId(Long jpRegionId) {
        JpRegionDo regionDo = baseMapper.selectById(jpRegionId);
        if (regionDo != null)
            return regionDo.getJpStateId();
        else {
            return 0L;
        }
    }

    /**
     * 通过postCode 获取县
     *
     * @param code 邮编
     * @return 获取到的都道府县
     */
    @Override
    public JpRegionDo getRegionDoByPostCode(String code) {
        QueryWrapper<JpRegionDo> wrapper = new QueryWrapper<>();
        String post2;
        int postcode;
        try {
            String regEx = "[^0-9||^０-９]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(code);
            post2 = m.replaceAll("").trim();
            post2 = post2.replaceAll("-", "");
            if (post2.length() > 7) {
                post2 = post2.substring(0, 7);
            }
            postcode = Integer.parseInt(post2);
        } catch (NumberFormatException | NullPointerException e) {
            e.printStackTrace();
            return null;
        }
        if (postcode < 100000) {
            //北海道特殊地区
            postcode = 400001;
        }
        wrapper.le("post_code_start", postcode);
        wrapper.ge("post_code_end", postcode);
        return baseMapper.selectOne(wrapper);
    }

}
